package web.admin.components;

import domain.shop.Product;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.admin.ShopAdminService;

import java.util.Iterator;

public class SortableProductDataProvider extends SortableDataProvider<Product> {
    /**
     * constructor
     */
    @SpringBean
    private ShopAdminService adminService;

    public SortableProductDataProvider() {
        // set default sort
        setSort("name", true);
        InjectorHolder.getInjector().inject(this);
    }

    /**
     * @see org.apache.wicket.markup.repeater.data.IDataProvider#iterator(int, int)
     */
    public Iterator<Product> iterator(int first, int count) {
        SortParam sp = getSort();
        return adminService.findProducts(first, count, getSort().getProperty(), getSort().isAscending()).iterator();
    }

    /**
     * @see org.apache.wicket.markup.repeater.data.IDataProvider#size()
     */
    public int size() {
        return adminService.getProductsCount();
    }

    /**
     * @see org.apache.wicket.markup.repeater.data.IDataProvider#model(java.lang.Object)
     */
    public IModel<Product> model(Product object) {
        final Long id = object.getId();
        return new LoadableDetachableModel<Product>() {
            @Override
            protected Product load() {
                return adminService.findProductById(id);
            }
        };
    }

}
